/**
 * @filename:SysAdminController 2022年1月27日
 * @project Wonder xhadmin Framework  V1.0
 * Copyright(c) 2020 LuZhongren Co. Ltd. 
 * All right reserved. 
 */
package com.wonder.admin.controller;



import com.wonder.admin.domain.SysAction;
import com.wonder.admin.domain.SysAdmin;
import com.wonder.admin.domain.SysMenu;
import com.wonder.admin.service.SysActionService;
import com.wonder.admin.service.SysAdminService;
import com.wonder.admin.service.SysMenuService;
import com.wonder.admin.request.SysAdminRequest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wonder.common.common.AjaxMap;
import com.wonder.common.common.AjaxResult;
import com.wonder.common.common.CommonPage;
import com.wonder.common.utils.MessageUtils;
import com.wonder.common.utils.StringUtils;
import com.wonder.common.utils.ThreadLocalUtil;
import com.wonder.utils.DBUtils;
import com.wonder.framework.aspect.annotation.Log;
import com.wonder.framework.aspect.enums.BusinessType;
import com.wonder.common.utils.GoogleAuthenticator;
import com.wonder.common.utils.sign.Md5Utils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**   
 * 
 * <p>说明： 后台用户管理API接口层</P>
 * @version: V1.0
 * @author: LuZhongren
 * @time    2022年1月27日
 *
 */
@Api(tags = "后台用户管理")
@RestController
@CrossOrigin
@RequestMapping("/admin")
public class SysAdminController {
	
	@Autowired
	private SysAdminService sysAdminService;
	
	@Autowired
	private SysMenuService sysMenuService;
	
	@Autowired
	private SysActionService sysActionService;
	
	@Autowired
	private DBUtils dbUtils;
	
	@Log(title = "用户管理", businessType = BusinessType.OTHER)
	@ApiOperation(value = "后台用户管理列表")
	@RequestMapping(value = "/Adminuser/index", method = RequestMethod.POST)
	public Map<String, Object> index(@RequestBody SysAdminRequest sysAdminRequest) {
	
		Page<SysAdmin> page = new Page<SysAdmin>(sysAdminRequest.getPage(), sysAdminRequest.getLimit());
		List<SysAdmin> list = sysAdminService.selectList(sysAdminRequest, page);
		page.setRecords(list);
		//IPage<SysAdmin> list = sysAdminService.selectList(sysAdminRequest, page);
		Map<String, Object> map=new HashMap<>();
		map.put("data", CommonPage.restPage(page));
		Map<String, Object> map1=new HashMap<>();
		map1.put("role_ids", dbUtils.getDropDownList("select role_id,name from sys_role"));
		map.put("sql_field_data", map1);
		
		return AjaxMap.success(map);
	}
	
	/**
	 * @explain 查询对象  <swagger GET请求>
	 * @param   对象参数：id
	 * @return  JsonResult
	 * @author  LuZhongren
	 * @time    2022年1月27日
	 */
	@PostMapping("/Adminuser/getInfo")
	@ApiOperation(value = "获取后台用户管理对象", notes = "作者：LuZhongren")
	public AjaxResult<SysAdmin> getInfo(@RequestBody  SysAdmin user){
		
		if(user==null || user.getUser_id()==null) return AjaxResult.failed(MessageUtils.message("insert.parameter.error"));
		SysAdmin sysAdmin=sysAdminService.getById(user.getUser_id());
		if (null!=sysAdmin ) {
			 return AjaxResult.success(sysAdmin);
		}else {
			return AjaxResult.failed(MessageUtils.message("search.not.exist"));
		}
		
	}
	
	
	/**
	 * @explain 查询对象  <swagger GET请求>
	 * @param   对象参数：id
	 * @return  JsonResult
	 * @author  LuZhongren
	 * @time    2022年1月27日
	 */
	@PostMapping("/Adminuser/getFieldList")
	@ApiOperation(value = "获取分组对象下拉数据", notes = "作者：LuZhongren")
	public AjaxResult<Map<String, Object>> getFieldList(){
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("role_ids", dbUtils.getDropDownList("select role_id,name from sys_role"));
		return AjaxResult.success(map);		
	}
	
	/**
	 * @explain 删除对象
	 * @param   对象参数：id
	 * @return  JsonResult
	 * @author  LuZhongren
	 * @time    2022年1月27日
	 */
	@PostMapping("/Adminuser/delete")
	@ApiOperation(value = "删除", notes = "作者：LuZhongren")
	public AjaxResult<SysAdmin> delete(@RequestBody Map<String, Object> map){
		
		if(map==null) AjaxResult.failed(MessageUtils.message("input.parameter.error"));
		Long user_id=Long.parseLong(map.get("user_id").toString());
		if(user_id==1)  return AjaxResult.failed(MessageUtils.message("superadmin.cannot.delete"));
		
		SysAdmin sysAdmin=sysAdminService.getById(user_id);
		if (null!=sysAdmin) {
		  boolean rsg = sysAdminService.removeById(user_id);
		  if (rsg) {
			    return AjaxResult.success(MessageUtils.message("delete.success"));
		  }else {
			   return AjaxResult.failed(MessageUtils.message("delete.fail"));
		  }
		}else {
			 return AjaxResult.failed(MessageUtils.message("delete.not.exist"));
		}
	}
	
	/**
	 * @explain 添加
	 * @param   对象参数：SysAdmin
	 * @return  Boolean
	 * @author  LuZhongren
	 * @time    2022年1月27日
	 */
	@PostMapping("/Adminuser/add")
	@ApiOperation(value = "添加用户", notes = "作者：LuZhongren")
	public AjaxResult<SysAdmin> add(@RequestBody SysAdmin entity){

		if (null!=entity) {
			entity.setPwd(Md5Utils.hash(entity.getPwd()));
			boolean rsg = sysAdminService.save(entity);
			if (rsg) {
				return AjaxResult.success(MessageUtils.message("insert.success"));
			  }else {
				  return AjaxResult.failed(MessageUtils.message("insert.fail"));
			  }
		}else {
			return AjaxResult.failed(MessageUtils.message("insert.parameter.error"));
		}
	}
	
	/**
	 * @explain 修改
	 * @param   对象参数：SysAdmin
	 * @return  Boolean
	 * @author  LuZhongren
	 * @time    2022年1月27日
	 */
	@PostMapping("/Adminuser/update")
	@ApiOperation(value = "修改", notes = "作者：LuZhongren")
	public AjaxResult<SysAdmin> update(@RequestBody SysAdmin entity){
		if (null!=entity) {
			boolean rsg = sysAdminService.updateById(entity);
			if (rsg) {
				 return AjaxResult.success(MessageUtils.message("update.success"));
			  }else {
				  return AjaxResult.failed(MessageUtils.message("update.fail"));
			  }
		}else {
			return AjaxResult.failed(MessageUtils.message("update.not.exist"));
		}
	}
	
	/**
	 * @explain 修改
	 * @param   对象参数：SysAdmin
	 * @return  Boolean
	 * @author  LuZhongren
	 * @time    2022年1月27日
	 */
	@PostMapping("/Adminuser/updateExt")
	@ApiOperation(value = "修改字段", notes = "作者：LuZhongren")
	public AjaxResult<SysAdmin> updateExt(@RequestBody SysAdmin entity){
		if (null!=entity) {
			boolean rsg = sysAdminService.updateById(entity);
			if (rsg) {
				 return AjaxResult.success(MessageUtils.message("update.success"));
			  }else {
				  return AjaxResult.failed(MessageUtils.message("update.fail"));
			  }
		}else {
			return AjaxResult.failed(MessageUtils.message("update.not.exist"));
		}
	}
	
	
	/**
	 * @explain 重置密码
	 * @param   对象参数：SysAdmin
	 * @return  Boolean
	 * @author  LuZhongren
	 * @time    2022年1月27日
	 */
	@PostMapping(value = {"/Adminuser/resetPwd","/Base/resetPwd"})
	@ApiOperation(value = "重置密码", notes = "作者：LuZhongren")
	public AjaxResult<SysAdmin> resetPwd(@RequestBody Map<String, Object> map){
		if (null!=map) {
			String pwd=map.get("pwd").toString();
			String user_id=null;
			if(map.containsKey("user_id")) {
				user_id=map.get("user_id").toString();
			}
			if(user_id==null) {
				user_id=ThreadLocalUtil.get("id").toString();
			}
			if(StringUtils.isBlank(pwd)) return AjaxResult.failed(MessageUtils.message("user.pwd.empty"));
			if(StringUtils.isBlank(user_id)) return AjaxResult.failed(MessageUtils.message("update.not.exist"));
			SysAdmin entity=new SysAdmin();
			entity.setUser_id(Long.parseLong(user_id));
			entity.setPwd(Md5Utils.hash(pwd));
			boolean rsg = sysAdminService.updateById(entity);
			if (rsg) {
				 return AjaxResult.success(MessageUtils.message("update.success"));
			  }else {
				  return AjaxResult.failed(MessageUtils.message("update.fail"));
			  }
		}else {
			return AjaxResult.failed(MessageUtils.message("update.not.exist"));
		}
	}
	
	@PostMapping("/Adminuser/getGoogleKey")
	@ApiOperation(value = "获取谷歌密钥", notes = "作者：LuZhongren")
	public Map<String, Object> getGoogleKey(){	
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("googleKey", GoogleAuthenticator.generateSecretKey());
		return AjaxMap.success(map);
	}
	
	@PostMapping("/Base/getRoleMenus")
	@ApiOperation(value = "获取", notes = "作者：LuZhongren")
	public Map<String, Object> getRoleMenus(){
		
		List<Map<String, Object>> roleMenuList=getNodeMenus(1L, 0L);
		Map<String, Object> map=new HashMap<String, Object>();
		
		map.put("menus", roleMenuList);
		return AjaxMap.success(map);
	}
	
	
	@PostMapping("/Base/clearCache")
	@ApiOperation(value = "清除缓存", notes = "作者：LuZhongren")
	public Map<String, Object> clearCache(){	
		//Map<String, Object> map=new HashMap<String, Object>();
		return AjaxMap.success();
	}
	
	
	
	
	private List<Map<String, Object>> getNodeMenus(Long app_id,Long pid) {
		List<Map<String, Object>> menus=new ArrayList<>();
		List<SysMenu> list=sysMenuService.list(new QueryWrapper<SysMenu>().eq("app_id", app_id).eq("pid", pid).orderByAsc("sortid"));
		if(list!=null) {
			
			for(SysMenu item:list) {
				Map<String, Object> menu=new HashMap<String, Object>();
				menus.add(menu);
				menu.put("sortid", item.getSortid());
				menu.put("access", item.getController_name());
				menu.put("title", item.getTitle() +" "+"(/admin/"+item.getController_name()+")");
				List<SysMenu> subList=sysMenuService.list(new QueryWrapper<SysMenu>().eq("app_id", app_id).eq("pid", item.getPid()).orderByAsc("sortid"));
				List<Map<String, Object>> funcsList=getFuns(item);
				if(subList!=null) {	
					List<Map<String, Object>> submenus=getNodeMenus(app_id, item.getMenu_id());
					if(!funcsList.isEmpty()) {
						funcsList.addAll(submenus);
						menu.put("children", funcsList);
		
					}else {
						menu.put("children", submenus);
					}
					
				}else {
					menu.put("children", funcsList);
					
				}

			}
			
		}
		return menus;
		

	}
	
	private List<Map<String, Object>> getFuns(SysMenu menu) {
		List<Map<String, Object>> funcs=new ArrayList<>();
		List<SysAction> list=sysActionService.list(new QueryWrapper<SysAction>().eq("menu_id", menu.getMenu_id()).orderByAsc("sortid"));
		if(list!=null) {
			
			for(SysAction item:list) {
				Map<String, Object> func=new HashMap<String, Object>();
				func.put("title", item.getName()+" " + "/"+menu.getModule()+"/" + menu.getController_name()+"/"+item.getAction_name() +".html");
				func.put("access",  "/"+menu.getModule()+"/" + menu.getController_name()+"/"+item.getAction_name() +".html");
				funcs.add(func);	
			}
		}
		return funcs;
	}
	
	
	
	
}